﻿//This file is part of XCOM ModManager

// XCOM ModManager is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace XCMod
{
    public partial class Form1 : Form
    {
        public static String appPath = Application.StartupPath;//application path
        public static string configPath = appPath + "\\config\\";//folder for config file
        public static string installationRoot;//XCOM installation root
        public static string unpackedRoot;//unpacked root
        public static string modAuthor;//mod author
        bool hasConfig;//do we already have config info?

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (Directory.Exists(configPath))//check if application config directory exists
            {
                if (File.Exists(configPath + "config.xml"))//check if config file exists
                {
                    //read the values from the xml file
                    readConfig();                    
                }
                else//if no config file exists
                {
                    hasConfig = false;
                    DialogResult result = MessageBox.Show("Would you like to configure XCOM Mod Manager?", "Configure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);//do you want to configure?
                    if (result == DialogResult.Yes)
                    {
                        //turn on timer, allow it to open config window
                        timer1.Enabled = true;
                    }
                }
            }
            else
            {
                hasConfig = false;
                Directory.CreateDirectory(configPath);//create the config directory
                DialogResult result = MessageBox.Show("Would you like to configure XCMod?", "Configure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);//do you want to configure?
                if (result == DialogResult.Yes)
                {
                    //open config window
                    //Config configForm = new Config(configPath);
                    timer1.Start();
                    //configForm.Show();
                }
            }
            if (hasConfig == true)
            {
                
            }
        }

        public void readConfig()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(configPath + "config.xml");
            XmlNode node = xml.DocumentElement.SelectSingleNode("XCOM");
            installationRoot = node.InnerText;
            node = xml.DocumentElement.SelectSingleNode("Unpacked");
            unpackedRoot = node.InnerText;
            node = xml.DocumentElement.SelectSingleNode("ModAuthor");
            modAuthor = node.InnerText;
            openFileDialog1.InitialDirectory = unpackedRoot;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void editConfigToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config configForm = new Config(configPath, this);//new instance of settings window
            configForm.loadFields(installationRoot, unpackedRoot, modAuthor);//populate that instance with current installation root
            configForm.Show();//show config window
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About aboutForm = new About();//new instance of about window
            aboutForm.Show();//show about window
        }

        //add filename to list of modded files
        private void btnAddModFile_Click(object sender, EventArgs e)
        {
           DialogResult result = openFileDialog1.ShowDialog();
           if (result == DialogResult.OK)
           {
               lbModFiles.Items.Add(openFileDialog1.FileName);
           }
        }

        //remove filename from list of modded files
        private void btnRmvModFile_Click(object sender, EventArgs e)
        {
            int currentSelection = lbModFiles.SelectedIndex;//currently selected item
            lbModFiles.Items.Remove(lbModFiles.SelectedItem);//remove selected item
            selectNext(currentSelection);//select the next item in the list
        }

        //selects the next entry in the list (not vitally important, but looks nice!)
        private void selectNext(int currSelect)
        {
            //variable to hold the number of items in the list
            int numOfEntries = lbModFiles.Items.Count;

            //if we have entries in the list, select the next entry
            if (numOfEntries > 0)
            {
                //if the selected entry was the last in the list
                if (numOfEntries == currSelect)
                {
                    //take one from currSelect in order to avoid error
                    currSelect--;
                }
                lbModFiles.SetSelected(currSelect, true);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //open config window
            Config configForm = new Config(configPath, this);
            configForm.Show();
            timer1.Stop();
            
        }

        private void btnCreateMod_Click(object sender, EventArgs e)
        {
            string modName = "";
            string modPath = "";
            Regex regExObj = new Regex("^[a-zA-Z0-9]*$");
            if (regExObj.IsMatch(tbModName.Text))
            {
                modName = tbModName.Text;//mod name
                modPath = appPath + "\\" + modName + "\\";//mod directory path
                if (Directory.Exists(modPath))//check if mod directory exists
                {
                    DialogResult result = MessageBox.Show("A mod with this name already exists, would you like to overwrite it?", "Mod Found", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)//overwrite
                    {
                        createModFile(modName, modPath);//create the mod file
                    }
                    if (result == DialogResult.No)//do not overwrite
                    {

                    }
                }
                else //create directory and make mod config file
                {
                    Directory.CreateDirectory(modPath);//create the mod directory
                    createModFile(modName, modPath);//create the mod file
                }
            }
            else
            {
                MessageBox.Show("Please enter your mod name in valid foldername format");
            }

            
        }

        private void createModFile(string modName, string modPath)
        {

            XmlDocument modConfigXML = new XmlDocument();//create new XML document
            XmlNode node = modConfigXML.CreateNode(XmlNodeType.XmlDeclaration, "", "");//create xml declaration
            modConfigXML.AppendChild(node);//append declaration to xml doc
            //<ModConfig> and its children
            XmlElement rootNode = modConfigXML.CreateElement("ModConfig");//create parent node
            //<ModName>
            XmlElement modNameElem = modConfigXML.CreateElement("ModName");//create modName element
            modNameElem.InnerText = modName;//element data
            rootNode.AppendChild(modNameElem);//append element to parent node
            //<ModAthor>
            XmlElement modAuthorElem = modConfigXML.CreateElement("ModAuthor");//create modAuthor element
            modAuthorElem.InnerText = modAuthor;//element data
            rootNode.AppendChild(modAuthorElem);//append element to parent node
            //<ModDescription>
            XmlElement descriptionElem = modConfigXML.CreateElement("ModDescription");//create modDescription element
            descriptionElem.InnerText = tbDescription.Text;//element data
            rootNode.AppendChild(descriptionElem);//append element to parent node
            //<Filepaths> and its children
            XmlElement filePathsElem = modConfigXML.CreateElement("Filepaths");//create data element
            //WILL NEED A LOOP FOR EACH INDEX IN LISTBOX
            for (int i = 0; i < lbModFiles.Items.Count; i++)
            {
                //  <Original>
                XmlElement origFileElem = modConfigXML.CreateElement("Original");//create UPKFilename element
                lbModFiles.SetSelected(i, true);//set selected item in listbox to current file
                string upkPath = lbModFiles.SelectedItem.ToString();//set string to selected item
                string upkName = upkPath.Substring(unpackedRoot.Length);//parse out the <unpacked> string
                origFileElem.InnerText = lbModFiles.GetItemText(upkName);//set element text to string
                filePathsElem.AppendChild(origFileElem);//append element to parent node
            }
            //END LOOP FOR EACH INDEX IN LISTBOX
            rootNode.AppendChild(filePathsElem);//append filepaths to parent node

            modConfigXML.AppendChild(rootNode);//append parent node to file
            try
            {
                modConfigXML.Save(modPath + modName + "Config");//save the xml doc
                MessageBox.Show(modName + " mod folder has been created.");
            }
            catch (Exception ex)
            {
                //error handling
            }
        }

        private void btnClearModFile_Click(object sender, EventArgs e)
        {
            lbModFiles.Items.Clear();
        }

        private void viewReadMeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(appPath + "\\README.txt");
        }

        private void btnModMaker_Click(object sender, EventArgs e)
        {
            var processInfo = new ProcessStartInfo("java.exe", "-jar ModMaker.jar")
            {
                CreateNoWindow = true,//won't show command window
                UseShellExecute = false
            };
            processInfo.WorkingDirectory = appPath; // this is where your jar file is.
            string args = "\"" + tbModName.Text + "\"";
            MessageBox.Show(args);
            processInfo.Arguments = "-jar " + appPath +"\\ModMaker.jar " + args;//name of mod (and mod folder) as argument
            Process proc;

            if ((proc = Process.Start(processInfo)) == null)
            {
                throw new InvalidOperationException("??");
            }
            //Process.Start(processInfo);
            proc.WaitForExit();
            int exitCode = proc.ExitCode;
            proc.Close();
            if (exitCode != 0)
            {
                MessageBox.Show("Mod creation unsuccessful, exit code " + exitCode, "Unable to Create Mod", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Mod creation successful, exit code" + exitCode);
            }
        }

        private void btnInstallMod_Click(object sender, EventArgs e)
        {
            var processInfo = new ProcessStartInfo("java.exe", "-jar ModInstaller.jar")
            {
                CreateNoWindow = true,//won't show command window
                UseShellExecute = false
            };
            processInfo.WorkingDirectory = appPath; // this is where your jar file is.
            string args = "\"" + tbInstallModName.Text + "\"";
            processInfo.Arguments = "-jar " + appPath + "\\ModInstaller.jar " + args;//name of mod (and mod folder) as argument
            Process proc;

            if ((proc = Process.Start(processInfo)) == null)
            {
                throw new InvalidOperationException("??");
            }

            proc.WaitForExit();
            int exitCode = proc.ExitCode;
            proc.Close();
            if (exitCode != 0)
            {
                MessageBox.Show("Mod installation unsuccessful, exit code " + exitCode, "Unable to Install Mod", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Mod installation successful, exit code " + exitCode);
            }
        }

        private void btnInstallModSelect_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                tbInstallModName.Text = openFileDialog1.FileName;
            }
        }
               
    }
}
